#!/usr/bin/python
#coding:utf-8
# Author:   --<>
# Purpose: 
# Created: 2010-01-08

import sys
from persistent import Persistent
from ZODB import FileStorage,DB
from BTrees.OOBTree import OOBTree
import transaction,traceback


DOC_DB = "doc_db"
TAG_DB = "tag_db"

class Doc(Persistent):pass 
class Tag(Persistent):pass 
class Sendto(Persistent):pass 
    
class Store:
    def __init__(self):
        self.store = FileStorage.FileStorage("jtkit.fs")
        self.db = DB(self.store)
        self.conn = self.db.open()
        self.dbroot = self.conn.root() 

    def close(self):
        #关闭数据库，释放资源
        try:
            self.conn.close()
            self.db.close()
            self.store.close()
            return True           
        except:
            return False
                    
    def _nextId(self):
        #获得一个全局序列号
        dbroot = self.dbroot
        try:
            if not dbroot.has_key("next_id"):
                dbroot["next_id"] = 0
            dbroot["next_id"] +=1
            transaction.commit()
            return dbroot["next_id"]
        except:
            return -1     
        
    def add(self,obj,dbname):
        #存储对象到指定名称数据库
        if not obj or not dbname:
            return
        dbroot = self.dbroot
        try:
            if not dbroot.has_key(dbname):
                dbroot[dbname]  = OOBTree()
            odb = dbroot[dbname]
            if not hasattr(obj,"id") or obj.id is None:
                obj.id = self._nextId()
            odb[obj.id] = obj
            transaction.commit()
            return True
        except:
            return False  
            
    def get(self,id,dbname):
        #从指定数据库查询指定id的对象
        if not id or not dbname:return
        dbroot = self.dbroot
        try:
            if dbroot.has_key(dbname):
                return dbroot[dbname][id]
        except:
            return None
            
    def remove(self,id,dbname):
        #按id删除对象
        if not id or not dbname:return
        dbroot = self.dbroot
        try:
            if dbroot.has_key(dbname) and dbroot[dbname][id]:
                del dbroot[dbname][id]
                transaction.commit()
                return True
        except:
            traceback.print_exc()
            return False
        
            
    def getAll(self,dbname,tag=None,keyword=None):
        #查询对象，可选标签
        if not dbname:return
        dbroot = self.dbroot
        try:
            if not dbroot.has_key(dbname):
                return None
            values = dbroot[dbname].values()
            if values:
                return [it for it in values if self._fliter(it,tag,keyword)]
            else:
                return values or []
        except:
            return []
        
    def _fliter(self,item,tag=None,keyword=None):
        if not tag and not keyword:
            return True
        if keyword:
            if item.content.find(keyword)!=-1:
                return True
        if tag:
            if item.tag == tag:
                return True
        return False
           
    def setTag(self,tag):
        if not tag:
            return
        dbroot = self.dbroot
        try:
            if not dbroot.has_key(TAG_DB):
                dbroot[TAG_DB]  = OOBTree()
            tagdb = dbroot[TAG_DB]
            tagdb[tag.name] = tag
            transaction.commit()
            return True
        except:
            return False  
        
    def getTag(self,tagname):
        if not tagname:return
        dbroot = self.dbroot
        try:
            if dbroot.has_key(TAG_DB):
                return dbroot[TAG_DB][tagname]
        except:
            return None
        
    def getAllTags(self):
        dbroot = self.dbroot
        try:
            if dbroot.has_key(TAG_DB):
                return dict(dbroot[TAG_DB].items())
        except:
            traceback.print_exc()
            return {}
        
    def removeTag(self,tagname):
        if not tagname:return
        dbroot = self.dbroot
        try:
            if dbroot.has_key(TAG_DB) and dbroot[TAG_DB][tagname]:
                del dbroot[TAG_DB][tagname]
                transaction.commit()
                return True
        except:
            return False        
        
    def addDoc(self,doc):
        return self.add(doc,DOC_DB)
        
    def removeDoc(self,id):
        return self.remove(id,DOC_DB)
        
    def getDoc(self,id):
        return self.get(id,DOC_DB)
    
    

if __name__=='__main__':
    """"""
    db = Store()
    print db.getAllTags()
    
    
    
    